<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Links extends AdminController {
	
	var $num_elements = 10;
	
	function Links(){
		parent::AdminController();
		
		$this->load->library('Form_validation');
		$this->load->model ( "Link_Model" , "Links" );
		$this->load->model ( "Category_Model", "Categories");
		
		$this->load->helper('date');
		
		$num_elements = $this->settings->item("_admin_list_elements");
		if($num_elements != NULL){
			$this->num_elements = $num_elements;
		}
	}
	
	function index(){
		$this->load->library('pagination');
		
		$pag = $this->pagination->segment_value();
		if($pag == NULL){
			$pag = 0;			
		}
		
		$params = array(
			"status" 		=> "all",
			"order"			=> array(
				"link_created" => "desc"
			)
		);
		
		$total = $this->Links->getCount(array("status" => "all", "hide_empty" => FALSE));
		$elements_process = $this->Links->get(array("status" => "all", "num_nodes" => TRUE, "hide_empty" => FALSE), $pag, $this->num_elements);
		
		$elements_tmp = array();
		foreach($elements_process as $el){
			$categories = $this->Links->getCategories($el->link_id);
			$el->categories = $categories;
			
			array_push($elements_tmp, $el);
		}
		
		$elements_process = $elements_tmp;
		
		$config['base_url'] = "/admin/links/index/";
		$config['total_rows'] = $total;
		$config['per_page'] = $this->num_elements;
		//$config['uri_segment'] = 4;
		
		$config['full_tag_open'] = '<div class="pagination">';
		$config['full_tag_close'] = '</div>';
		
		$config['num_tag_open'] = '<span class="number">';
		$config['num_tag_close'] = '</span>';
		
		$config['cur_tag_open'] = '<span class="number current">';
		$config['cur_tag_close'] = '</span>';
		
		$config['first_link'] = 'Inicio';
		$config['last_link'] = 'Último';
		$config['prev_link'] = '&lt; Ant';
		$config['next_link'] = 'Sig &gt;';

		$this->pagination->initialize($config);
		
		$this->_addData("elements", $elements_process);
		
		$this->_render();
		
	}
	
	function add(){
		$this->_setPageView("links/form");
		
		$this->form_validation->set_rules('name', 'Nombre', 'required|max_length[60]');
		$this->form_validation->set_rules('url', 'Url', 'required|max_length[200]');
		$this->form_validation->set_rules('status', 'Estado', 'required');

		if ($this->form_validation->run() == TRUE)
		{
			$fields = array(
				'name'		=> $this->input->post('name'),
				'url'		=> $this->input->post('url'),
				'status'	=> $this->input->post('status'),
			);
			
			$id = $this->Links->create($fields);
			
			//Obtenemos las categorias seleccionadas
			$categories = $this->input->post("categories");
			$this->Links->addCategories($id, $categories);
			
			$this->_process_extra_info($id);
			
			$this->_addFlashSuccess("Enlace creada correctamente");
			redirect('admin/links', 'refresh');
		} else{
			$this->_addData("categorias", $this->Categories->get(array("status" => "all")));
			$this->_pre_process_extra_info();
		}
		
		$this->_render();
	}
	
	function edit($id = NULL){
		$this->_setPageView("links/form");
		
		$this->form_validation->set_rules('name', 'Nombre', 'required|max_length[60]');
		$this->form_validation->set_rules('url', 'Url', 'required|max_length[200]');
		$this->form_validation->set_rules('status', 'Estado', 'required');
		$this->form_validation->set_error_delimiters('', '<br />');

		if ($this->form_validation->run() == TRUE){
			$fields = array(
				'id'		=> $id,
				'name'		=> $this->input->post('name'),
				'url'		=> $this->input->post('url'),
				'status'	=> $this->input->post('status'),
			);
			
			$this->Links->update($fields);
			
			$this->Links->deleteCategories($id);
			//Obtenemos las categorias seleccionadas
			$categories = $this->input->post("categories");
			$this->Links->addCategories($id, $categories);
			
			$this->_process_extra_info($id);
			
			$this->_addFlashSuccess("Enlace modificado correctamente");
			redirect('admin/links', 'refresh');
			
		} else{				
		
			if($id != NULL){
				$elemento = $this->Links->get(array("id" => $id, "status" => "all"));
				
				if($elemento !== FALSE){
					$this->_addData("elemento", $elemento);
				}
				
				$this->_addData("id", $id);
				$this->_addData("categorias", $this->Categories->get(array("status" => "all")));
				$this->_addData("selected_categories",  $this->Links->getCategories($id));
				$this->_pre_process_extra_info($id);
			}
		}
		
		$this->_render();
	}
	
	function delete($id) {
		if($id != null){
			$this->Links->delete($id);
			$this->_addFlashSuccess("Enlace eliminado correctamente");
		}
		
		redirect ( 'admin/links', 'refresh' );
	}
	
	
	function _pre_process_extra_info($id = NULL){
		$extra_fields = $this->settings->item("links_columns");
		
		$process_extra_fields = array();
		foreach($extra_fields as $field_name=>$field_info){
			$process_extra_fields[$field_name] = $field_info;
			
			if($id != NULL){
				$f = $this->Links->getMeta($id, $field_name, TRUE);
				if($f != NULL){
					$process_extra_fields[$field_name]['value'] = $f->meta_value;
				}
			}
		}
		
		$this->_addData("extra_fields", $process_extra_fields);
	}
	
	function _process_extra_info($id = NULL){
		if($id != NULL){
			$extra_fields = $this->settings->item("links_columns");
			
			foreach($extra_fields as $field_name=>$field_info){
				//Temporal. Tendremos que crear una libreria para tratar form_field
				// lib->get($name)
				
				$old_value = $this->Links->getMeta($id, $field_name, TRUE);
				if($old_value != NULL){
					$old_value = $old_value->meta_value;
				}
				
				Console::log("OLD VALUE: " . $old_value);
				
				$value = NULL;
				if(isset($field_info['default'])){
					$value = $field_info['default'];
				}
				
				if($field_info['type'] ==  "file"){
					$value = $old_value;
					
					Console::log("Tipo FILE. Nombre del campo: $field_name");
					
					$this->load->library('upload');
					
					$default['upload_path'] = "upload";
					$default['allowed_types'] = 'gif|jpg|png';
					
					$config = array_merge($default, $field_info);
					
					if(!file_exists($config['upload_path'])){
						mkdir($config['upload_path'], 0777, true);
					}
					
					Console::log("UPLOAD PATH: " . $config['upload_path']);
					
					$this->upload->initialize($config);
					
					if ($this->upload->do_upload($field_name)){
						$data = $this->upload->data();
						Console::log("UPLOAD CORRECTO. Data: " . print_r($data, TRUE));
						
						$value = $data['full_path'];
						$value = substr($value, strpos($value, $config['upload_path']));
						if($old_value != NULL && file_exists($old_value)){
							unlink($old_value);
						}
					} else{
						Console::log("ERROR EN EL UPLOAD!!!!!!" . $this->upload->display_errors());
					}
				} else{
					$value = $this->input->post($field_name);
				}
				
				
				if($value != NULL){
					
					if($old_value != NULL && $value != $old_value){
						$this->Links->updateMeta($id, $field_name, $value);
					} else {
						$this->Links->addMeta($id, $field_name, $value, TRUE);
					}
				}
			}
		}
	}
	
}